package com.dhcc.controller;

import com.dhcc.SnowflakeIdWorker;
import com.dhcc.api.R;
import com.dhcc.httpApiService.IdGeneratorService;
import com.dhcc.service.ReactiveRedisService;
import com.dhcc.service.RedisService;
import com.dhcc.util.ContextUtil;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.Disposable;
import reactor.core.publisher.Mono;

/**
 * @ProjectName Dhcc-Cloud
 * @PackageName com.dhcc.redis
 * @Title controller
 * @Date 2024/10/4 下午9:55
 * @Author LiuGuoting
 */
@RestController
@RequestMapping("/demo")
public class DemoController {
    @Resource
    private ReactiveRedisService reactiveRedisService;
    @Resource
    private RedisService redisService;
    @Resource
    private SnowflakeIdWorker snowflakeIdWorker;
    @Resource
    private IdGeneratorService idGeneratorService;

    @PostMapping("/setReactiveRedis")
    public Disposable reactiveSet(@RequestBody String key, String value) {
        return reactiveRedisService.save(key, value)
                // 直接使用布尔值作为状态码，成功为true，失败为false
                .map(R::status)
                // 处理异常情况，返回失败状态码
                .onErrorReturn(R.status(false))
                .subscribe(result -> System.out.println("result:" + result),
                        error -> System.err.println("error:" + error));
    }
    @GetMapping("/getReactiveRedis")
    public Mono<ResponseEntity<Object>> reactiveGet(@RequestParam String key) {
        return reactiveRedisService.get(key)
            // 处理成功情况，返回值
                .map(value -> ResponseEntity.ok(value))
                // 处理异常情况，返回错误信息
                .onErrorReturn(ResponseEntity.status(500).body("Error fetching from Redis"))
                // 如果值为 null，返回 404 状态码
                .defaultIfEmpty(ResponseEntity.notFound().build());
    }

    @PostMapping("/setRedis")
    public R setRedis(@RequestBody String key,@RequestBody String value) {
        redisService.setCacheObject(key, value);
        return R.success();
    }
    @GetMapping("/getRedis")
    public R getRedis(@RequestParam String key) {
        Object cacheObject = redisService.getCacheObject(key);
        return R.data(cacheObject);
    }

    @GetMapping("/getNextId")
    public R getNextId() {
        long nextId = snowflakeIdWorker.nextId();
        return R.data(nextId);
    }

    @GetMapping("/getNextIdService")
    public R getNextIdService() {
        Long nextId = idGeneratorService.nextId();
        return R.data(nextId);
    }
    @GetMapping("/getUserId")
    public R getUserId() {
        // 使用工具类获取用户 ID
        // String userId = ContextUtil.getGatewayHeader();
        String userId = ContextUtil.getUserId();
        return R.data(userId);
    }
    @GetMapping("/test")
    public R test() {
        return R.data("你好呀");
    }
}
